/*
 * 精读编辑
 */
import * as React from 'react';
import { connect } from 'react-redux';
import SortableItem from './SortableItem';

interface SortableListProps {
  items: any[];
  onSorted: (keys: any[]) => any;
}
interface SortableListState {
  items: any[];
}
class SortableList extends React.Component<SortableListProps, SortableListState> {
  static defaultProps: SortableListProps = {
    onSorted: () => {},
    items: [],
  };

  onSortItems = (items: any) => {
    const keys = items.map((item: any) => {
      return item.key;
    });
    this.props.onSorted(keys);
  };

  render() {
    const { items } = this.props;
    const listItems = items.map((item: any, i: number) => {
      return (
        <SortableItem key={i} onSortItems={this.onSortItems} items={items} sortId={i}>
          {item}
        </SortableItem>
      );
    });

    return (
      <ul style={{ listStyle: 'none', padding: 0 }} className="sortable-list">
        {listItems}
      </ul>
    );
  }
}

interface OwnProps {
  onSorted: (keys: any[]) => any;
  items: any[];
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { items, onSorted } = ownProps;

  return {
    items,
    onSorted,
  };
}

export default connect(mapStateToProps)(SortableList);
